package com.lkd.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lkd.dto.LoginDTO;
import com.lkd.dto.UserDTO;
import com.lkd.exception.LoginException;
import com.lkd.mapper.UserMapper;
import com.lkd.result.TableInfo;
import com.lkd.service.UserService;
import com.lkd.vo.LoginUserVO;
import com.lkd.entity.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

import static com.github.pagehelper.page.PageMethod.startPage;

/**
 * @Author: Z.lx
 * @Date: 2025/8/16 21:29
 * @Description:
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginUserVO login(LoginDTO dto) {
        if(dto == null){
            //参数异常
            throw new LoginException("参数异常");
        }
        User user = userMapper.login(dto.getLoginName(),dto.getPassword());

        if(user == null){ //代表用户不存在
            throw new LoginException("用户不存在");
        }
        if(!user.getPassword().equals(dto.getPassword())){ //代表密码错误
            throw new LoginException("密码错误");
        }
        //密码相等
        LoginUserVO loginUserVo = new LoginUserVO();
        loginUserVo.setUserId(user.getId());
        loginUserVo.setUserName(user.getUserName());
        loginUserVo.setRoleCode(user.getRoleCode());
        loginUserVo.setSuccess(true);
        loginUserVo.setMsg("登录成功");
        loginUserVo.setToken(UUID.randomUUID().toString());
        return loginUserVo;
    }

    @Override
    public TableInfo<User> list(UserDTO userDTO) {
        PageHelper.startPage(userDTO.getPageIndex(), userDTO.getPageSize());
        List<User> userList = userMapper.list(userDTO.getUserName());
        Page< User> page = (Page< User>) userList;
        return new TableInfo<>(userDTO.getPageIndex(), userDTO.getPageSize(), page.getPages(), page.getTotal(), userList);
    }

    @Override
    public Boolean add(User user) {
        return userMapper.insertUser(user);
    }

    @Override
    public Boolean update(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public int delete(Long id) {
        return userMapper.deleteByUserId(id);
    }
}
